package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.constans.CacheConstants;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 报警规则Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-14
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }


    //报警过滤
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public void alertFilter() {
        //查询所有的规则
        long count = count(Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1));
        if (count <= 0){
            return;
        }
        //查询所有上报的数据
        List<Object> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)){
            return;
        }
        //解析上报的数据
        List<DeviceData> deviceDatas = new ArrayList<>();
        values.forEach(v -> {
            deviceDatas.addAll(JSONUtil.toList(v.toString(), DeviceData.class));
        });
        //获取报警规则，进行匹配
        deviceDatas.forEach(d ->alertFilter(d));

    }

    //逐条过滤报警数据
    private void alertFilter(DeviceData d) {
        //判断当前上报的数据是否超过了一分钟
        LocalDateTime alarmTime = d.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60){
            return;
        }
        //查询所有的该产品规则和该物模型的规则
        List<AlertRule> alertRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey, d.getProductKey())
                .eq(AlertRule::getFunctionId, d.getFunctionId())
                .eq(AlertRule::getIotId,"-1")
                .eq(AlertRule::getStatus, 1));
        List<AlertRule> iotIdRules = list(Wrappers.<AlertRule>lambdaQuery()
                .eq(AlertRule::getProductKey,d.getProductKey())
                .eq(AlertRule::getFunctionId,d.getFunctionId())
                .eq(AlertRule::getIotId,d.getIotId())
                .eq(AlertRule::getStatus, 1));
        //合并
        Collection<AlertRule> allArertRules = CollUtil.addAll(alertRules, iotIdRules);
        if (CollUtil.isEmpty(allArertRules)){
            return;
        }
        //按照过滤规则和上报的数据进行匹配
        allArertRules.forEach(alertRule -> deviceDataAlarmHanfler(alertRule,d));
    }

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;

    //过滤数据是否触发报警规则
    private void deviceDataAlarmHanfler(AlertRule rule, DeviceData deviceData) {
        String[] split = rule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(split[0]);
        LocalTime endTime = LocalTime.parse(split[1]);
        //获取上报时间
        LocalTime time = LocalDateTimeUtil.of(deviceData.getAlarmTime()).toLocalTime();
        if (time.isBefore(startTime) || time.isAfter(endTime)){
            return;
        }
        //获取IOTID
        String iotId = deviceData.getIotId();
        //统计次数的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX+ iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        //数据对比，上报的数据与规则中的阈值进行对比
        int compare = NumberUtil.compare(Double.valueOf(deviceData.getDataValue()), rule.getValue());
        if((rule.getOperator().equals(">=") && compare >= 0)
        || (rule.getOperator().equals("<") && compare < 0)){
            log.info("当前上报的数据符合规则异常！");
        }else {
            //正常的数据
            redisTemplate.delete(aggCountKey);
            return;
        }
        //判断是否在沉默周期内
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceData.getFunctionId() + ":" + rule.getId();
        String silentData = redisTemplate.opsForValue().get(silentKey);
        if (StringUtils.isNotEmpty(silentData)){
            return;
        }
        //持续周期的逻辑
        String aggData = redisTemplate.opsForValue().get(aggCountKey);
        int count = StringUtils.isEmpty(aggData) ? 1 : Integer.parseInt(aggData) + 1;
        if (ObjectUtil.notEqual(count, rule.getDuration())){
            redisTemplate.opsForValue().set(aggCountKey,count + "");
            return;
        }

        redisTemplate.delete(aggCountKey);
        redisTemplate.opsForValue().set(silentKey, "1",rule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //删除redis的报警数据
        List<Long> userIds = new ArrayList<>();
        if (rule.getAlertDataType().equals(0)){
            if (deviceData.getLocationType().equals(0)){
                userIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if (deviceData.getLocationType().equals(1) &&
                    deviceData.getLocationType().equals(2))
            {
                userIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        }else {
            userIds = userRoleMapper.selectUserIdByRoleName(deviceMaintainerRole);
        }
        //通知超级管理员
        List<Long> managerIds = userRoleMapper.selectUserIdByRoleName(managerRole);
        Collection<Long> allUserIds = CollUtil.addAll(userIds, managerIds);
        //去重
        allUserIds = CollUtil.distinct(allUserIds);

        //保存报警数据
        List<AlertData> alertDataList = insertAlertData(allUserIds,rule,deviceData);
        
        //websocket推送消息
        websocketNotity(alertDataList.get(0),rule,allUserIds);
    }

    private void websocketNotity(AlertData alertData, AlertRule rule, Collection<Long> allUserIds) {
        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(rule.getFunctionName());
        alertNotifyVo.setAlertDataType(rule.getAlertDataType());
        alertNotifyVo.setNotifyType(1);
        //向指定的人推送消息
        websocketServer.sendMessageToConsumer(alertNotifyVo,allUserIds);
    }

    @Autowired
    private WebSocketServer  websocketServer;
    @Autowired
    private IAlertDataService alertDataService;
    private List<AlertData> insertAlertData(Collection<Long> allUserIds, AlertRule rule, DeviceData deviceData) {
        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        //心率 ” < 60 “，持续3个周期就报警
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警",
                rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);
        alertData.setType(rule.getAlertDataType());
        //遍历allUserIds
        List<AlertData> list = allUserIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            dbAlertData.setId(null);
            return dbAlertData;
        }).collect(Collectors.toList());

        //批量保存
        alertDataService.saveBatch(list);
        return list;
    }



}
